from collections import OrderedDict
from pprint import pprint

from django.shortcuts import render
from django.views import View

from apps.goods.models import GoodsChannel, SKU


class IndexView(View):
    def get(self, request):
        """
        主页
        :param request:
        :return:
        """
        # 查询商品频道和分类
        categories_dict = OrderedDict()  # 创建一个有序的字典（先添加的key-value在前面）
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')
        for channel in channels:  # 总共是11个频道，每个频道中 基本上有3、4个商品类别
            group_id = channel.group_id  # 当前频道的id
            if group_id not in categories_dict:
                categories_dict[group_id] = {'channels': [], 'sub_cats': []}

            category_1 = channel.category  # 当前频道的 商品类别（1级分类）

            # 追加1级分类信息到当前频道
            categories_dict[group_id]['channels'].append({
                'id': category_1.id,
                'name': category_1.name,
                'url': channel.url
            })


            # 构建当前类别的子类别（2、3级分类）
            for category_2 in category_1.subs.all():
                # 将2级分类模型类对象中的信息，转换为字典
                category_2_dict = {"id": category_2.id, "name": category_2.name, "sub_cats": []}
                for category_3 in category_2.subs.all():
                    # 将3级分类模型类对象中的信息，转换为字典
                    category_3_dict = {"id": category_3.id, "name": category_3.name}
                    category_2_dict["sub_cats"].append(category_3_dict)
                categories_dict[group_id]['sub_cats'].append(category_2_dict)

        sku = SKU.objects.filter().all()
        # 渲染模板的上下文
        context = {
            'categories': categories_dict,
            'contents': sku[0:10],
        }

        return render(request, 'index.html', context)
